<?php
namespace app\modules\common\components;

use app\modules\common\exceptions\BusinessException;
use Exception;
use stdClass;
use yii;
use yii\base\Model;
use yii\web\Response;

class Common
{
    public static function codeReturn($data = [], $code = Api::CODE_SUCCESS, $desc = Api::MSG_SUCCESS)
    {
        return compact('code', 'data', 'desc');
    }

    public static function jsonReturn($code, $message = "", $data = [])
    {
        yii::$app->response->format = Response::FORMAT_JSON;

        if (empty($data)) {
            $data = new stdClass();
        }

        $result = [
            'code' => $code,
            'desc' => $message,
            'data' => $data
        ];
        return $result;
    }

    public static function recordBusinessReturn(BusinessException $businessException, $source)
    {
        self::recordInfo($businessException, $source);
        return self::codeReturn($businessException->getData(), $businessException->getCode(), $businessException->getMessage());
    }

    private static function recordInfo(Exception  $exception, $source)
    {
        //记录日志信息
        $logInfo = new LogFormat("exception", $source, $exception->getLine(), $exception->getMessage());
        YiiLog::info($logInfo->format());
        unset($logInfo);
    }

    public static function recordReturn(Exception $exception, $source)
    {
        self::recordInfo($exception, $source);
        return self::codeReturn([], $exception->getCode(), $exception->getMessage());
    }


    public static function errorMessage(Model $model)
    {
        $message = "";
        $tmpArr = $model->getFirstErrors();
        foreach ($model->activeAttributes() as $ati) {
            if (isset($tmpArr[$ati]) && !empty($tmpArr[$ati])) {
                $message = $tmpArr[$ati];
                break;
            }
        }

        return self::codeReturn([], Api::CODE_ERROR, $message);
    }
}
